package com.shiguiwu.springmybatis.spring.aop.principle.factory;

import org.springframework.aop.framework.AopContext;
import org.springframework.core.NamedThreadLocal;
import org.springframework.lang.Nullable;

/**
 * @description:
 * @author: stone
 * @date: Created by 2021/6/4 15:26
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.spring.aop.principle.factory
 */
public class MyAopContext {

    private static final ThreadLocal<Object> currentProxy = new NamedThreadLocal("Current AOP proxy");

    private MyAopContext() {
    }

    public static Object currentProxy() throws IllegalStateException {
        Object proxy = currentProxy.get();
        if (proxy == null) {
            throw new IllegalStateException("Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available, and ensure that AopContext.currentProxy() is invoked in the same thread as the AOP invocation context.");
        } else {
            return proxy;
        }
    }

    @Nullable
    static Object setCurrentProxy(@Nullable Object proxy) {
        Object old = currentProxy.get();
        if (proxy != null) {
            currentProxy.set(proxy);
        } else {
            currentProxy.remove();
        }

        return old;
    }
}
